<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb-base" style="line-height: 30px">
      <el-breadcrumb-item>
        <!--:to="{ path: '/application' }"-->
        <i class="el-icon-search"></i>
        <span>综合查询</span>
      </el-breadcrumb-item>
    </el-breadcrumb>

    <div class="main-container">
      <div class="filter">
        <div class="inner">
          <el-form ref="filterForm" :model="filterForm" label-width="70px" @submit.native.prevent>
            <el-row>
              <el-col :span="17">
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="病理编号">
                      <el-input class="input-form" size="mini" v-model="filterForm.pathologyId" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="切片用途">
                      <el-select v-model="filterForm.slicePurpose" placeholder="请选择切片用途" clearable class="picker-form"
                        size="mini">
                        <el-option v-for="item in sliceUsesList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="扫描日期">
                      <el-date-picker v-model="filterForm.scanRange" class="time-picker" size="mini" type="daterange"
                        unlink-panels range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" clearable>
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <div v-if="showExpansion">
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="患者姓名">
                        <el-input class="input-form" size="mini" v-model="filterForm.name" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="取材脏器" prop="pathologyHaslet">
                        <el-select v-model="filterForm.sampleOrganId" placeholder="请选择取材脏器" class="picker-form"
                          size="mini" clearable>
                          <el-option v-for="item in organDict" :key="item.value" :label="item.dicName"
                            :value="item.dicCode">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="送检医生">
                        <el-input class="input-form" size="mini" v-model="filterForm.sendDoctor" clearable>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="标本类别">
                        <el-select v-model="filterForm.specimenType" placeholder="请选择标本类别" class="picker-form" size="mini"
                          clearable>
                          <el-option v-for="data in specimenCategoryList" :key="data.id" :label="data.name"
                            :value="data.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="病区名称">
                        <el-input class="input-form" size="mini" v-model="filterForm.wardName" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="床位号">
                        <el-input class="input-form" size="mini" v-model="filterForm.bedId" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="取材部位">
                        <el-input class="input-form" size="mini" v-model="filterForm.sampleBody" clearable>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="标本名称">
                        <el-input class="input-form" size="mini" v-model="filterForm.specimenName" clearable>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="联系电话">
                        <el-input class="input-form" size="mini" v-model="filterForm.sendDoctorTel" clearable>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="病理诊断">
                        <el-input class="input-form" size="mini" v-model="filterForm.diagnosisDetailOfPathologyDiagnosis
                          " clearable>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="切片诊断">
                        <el-input class="input-form" size="mini" v-model="filterForm.slicePathologyDiagnosis" clearable>
                        </el-input>
                      </el-form-item>
                    </el-col>

                  </el-row>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item class="el-form-item" label="所属医院">
                        <el-select v-model="filterForm.sliceHospital" class="picker-form" size="mini"
                          @change="getBranchList">
                          <el-option v-for="t in hospitalList" :key="t.id" :label="t.name" :value="t.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item class="el-form-item" label="分院名称">
                        <el-select v-model="filterForm.branchName" placeholder="请选择分院" clearable class="picker-form"
                          size="mini">
                          <el-option v-for="item in branchCourtsList" :key="item.name" :label="item.name"
                            :value="item.name"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
              <el-col :span="7">
                <el-form-item>
                  <div class="expansion" @click="toggleExpansion">
                    <font-awesome-icon v-if="!showExpansion" :icon="['fas', 'angle-down']">
                    </font-awesome-icon>
                    <font-awesome-icon v-else :icon="['fas', 'angle-up']">
                    </font-awesome-icon>
                  </div>
                  <el-button type="primary" size="mini" @click="search" style="margin-left: 13px">
                    搜索
                  </el-button>
                  <el-button type="primary" size="mini" style="margin-left: 13px">
                    +科研库
                  </el-button>
                  <el-button type="primary" size="mini" style="margin-left: 13px">
                    +教学库
                  </el-button>
                  <!--<el-button size="mini"-->
                  <!--:loading="downloadbuttonloading"-->
                  <!--@click="downloadhospitalapplicationExcel">-->
                  <!--导出表格-->
                  <!--</el-button>-->
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <el-col :span="6">
          <el-form-item>
            <div class="expansion" @click="toggleExpansion">
              <font-awesome-icon v-if="!showExpansion" :icon="['fas', 'angle-down']">
              </font-awesome-icon>
              <font-awesome-icon v-else :icon="['fas', 'angle-up']">
              </font-awesome-icon>
            </div>
            <el-button type="primary" size="mini" @click="search" style="margin-left: 13px">
              搜索
            </el-button>
            <el-button type="primary" size="mini" style="margin-left: 13px">
              +科研库
            </el-button>
            <el-button type="primary" size="mini" style="margin-left: 13px">
              +教学库
            </el-button>
            <!--<el-button size="mini"-->
            <!--:loading="downloadbuttonloading"-->
            <!--@click="downloadhospitalapplicationExcel">-->
            <!--导出表格-->
            <!--</el-button>-->
          </el-form-item>
        </el-col>
      </div>
      <div class="application-list">
        <base-table ref="appAllTable" v-loading="loading" :data="appAllTable.data" :header="appAllTable.header"
          :operation="appAllTable.operation" :pageInfo="appAllTable.pageInfo" :selected="true"
          @handleClick="rolesTableButtonClick" @pageJumpTo="appAllTablePageJumpTo" @sizeChange="appAllTableSizeChange"
          @selectionChange="selectionChange" @handleSelectAll="handleSelectAll">
        </base-table>
      </div>
    </div>
  </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import _ from 'lodash';
import moment from 'moment/moment';
import { itemsPerPage, itemsCurrentPage } from '@/client/libs/util';

export default {
  name: 'IntegratedQuery',
  components: {
    BaseTable,
  },
  data() {
    return {
      BiopsyScanUrl: process.env.BiopsyScanUrl,
      selectedList: [],
      filterForm: {
        pathologyId: '',
        slicePurpose: '',
        diagnosisDetailOfPathologyDiagnosis: '',
        slicePathologyDiagnosis: '',
        scanRange: '',
        name: '',
        sampleOrganId: '',
        sendDoctor: '',
        wardName: '',
        bedId: '',
        sampleBody: '',
        sendDoctorTel: '',
        specimenName: '',
        specimenType: '',
        // page: 0,
        page: itemsCurrentPage.get() - 1,
        size: itemsPerPage.get(),
      },
      showExpansion: false,
      loading: true,
      appAllTable: {
        data: [],
        header: [
          {
            label: '分院名称',
            prop: 'branchName',
            width: '107',
          },
          {
            prop: 'pathologyId',
            label: '病理编号',
            width: 120,
          },
          {
            prop: 'diagnosisDetailOfPathologyDiagnosis',
            label: '病理诊断',
            width: 120,
          },
          {
            prop: 'currentLevelLabel',
            label: '状态',
          },
          {
            prop: 'name',
            label: '患者姓名',
            width: 107,
          },
          {
            prop: 'age',
            label: '年龄',
            width: 80,
          },
          {
            prop: 'sexName',
            label: '性别',
            width: 80,
          },
          {
            prop: 'cardId',
            label: '身份证号',
            width: 140,
          },
          {
            prop: 'wardName',
            label: '病区名称',
            width: 107,
          },
          {
            prop: 'bedId',
            label: '床位号',
            width: 107,
          },
          {
            prop: 'sampleOrganIdStr',
            label: '取材脏器',
            width: 107,
          },
          {
            prop: 'sampleBody',
            label: '取材部位',
            width: 107,
          },
          {
            label: '切片数',
            prop: 'biopsyCount',
            width: 107,
          },
          {
            label: '切片用途',
            width: '100',
            isRender: true,
            render: (h, params) => {
              let slicePurposeStr = '';
              if (params.row.comQuerySlicePurposeInfoList) {
                params.row.comQuerySlicePurposeInfoList.forEach((item) => {
                  if (item.slicePurposeName == null) {
                  } else {
                    slicePurposeStr =
                      slicePurposeStr + item.slicePurposeName + ' ';
                  }
                });
              }
              return h('span', slicePurposeStr);
            },
          },
          {
            label: '切片诊断',
            width: '120',
            isRender: true,
            render: (h, params) => {
              let sliceDiagnosisStr = '';
              if (params.row.comQuerySlicePathologyDiagnosisInfoList) {
                params.row.comQuerySlicePathologyDiagnosisInfoList.forEach(
                  (item) => {
                    if (item.slicePathologyDiagnosis == null) {
                    } else {
                      sliceDiagnosisStr =
                        sliceDiagnosisStr + item.slicePathologyDiagnosis + ' ';
                    }
                  }
                );
              }
              return h('span', sliceDiagnosisStr);
            },
          },
          {
            label: '扫描时间',
            width: '136',
            prop: 'createTime',
            // isRender: true,
            // render: (h, params) => {
            //     let biopsyScanTimeStr = '';
            //     if (params.row.biopsyScanTimeInfoList) {
            //         params.row.biopsyScanTimeInfoList.forEach(
            //             (item) => {
            //                 if (item.biopsyScanTime == null) {
            //                 } else {
            //                     biopsyScanTimeStr =
            //                         biopsyScanTimeStr +
            //                         item.biopsyScanTime +
            //                         ' ';
            //                 }
            //             }
            //         );
            //     }
            //     return h('span', biopsyScanTimeStr);
            // },
          },
          {
            label: '送检医生',
            prop: 'sendDoctor',
            width: 107,
          },
          // {
          //   label: '初诊医生',
          //   prop: 'firstDoctor',
          // },
          // {
          //   label: '申请时间',
          //   prop: 'createAt',
          //   width: 200,
          // },
          // {
          //   label: '诊断类型',
          //   prop: 'consultation',
          // },
          {
            label: '标本名称',
            prop: 'specimenName',
            width: 107,
          },
          {
            label: '标本类别',
            prop: 'specimenTypeStr',
            width: 107,
          },
          {
            label: '病人类别',
            prop: 'patientCategoryStr',
            width: 107,
          },
        ],
        operation: [
          {
            label: '详情',
            functionKey: 'checkDetail',
          },
          // {
          //     label: '报告',
          //     functionKey: 'previewReport',
          // },
          {
            label: '切片',
            functionKey: 'biopsyPicture',
          },
          {
            label: '标注',
            functionKey: 'biopsyMark',
          },
        ],
        pageInfo: {
          hide: false,
          page: 1,
          size: 15,
          total: 0,
        },
      },
      detailVisible: false,
      organDict: [],
      dictRequestMap: [
        {
          code: 'sliceUses',
          arrayKey: 'sliceUsesList',
        },
        {
          code: 'specimenCategory',
          arrayKey: 'specimenCategoryList',
        },
        {
          code: 'hospitalList',
          arrayKey: 'hospitalList',
        },
      ],
      sliceUsesList: [],
      specimenCategoryList: [],
      hospitalList: [],
      branchCourtsList: [], //分院列表
    };
  },
  mounted() {
    this.appAllDataRequest();
    this.getExamineOrganType();
    this.dictionariesRequest();
  },
  methods: {
    //获取分院列表
    getBranchList(id) {
      this.branchCourtsList = []
      let mData = this.hospitalList.filter((item) => item.id === id)[0]
      if (mData.firstCode) {
        mData.firstCode.split('、').forEach((item) => {
          this.branchCourtsList.push({ name: item })
        })
      }
    },
    // 字典数据请求
    async dictionariesRequest() {
      this.dictRequestMap.forEach((map) => {
        this.$axios({
          method: 'GET',
          url: '/PROXY-Remote/dicts/list',
          params: {
            code: map.code,
            page: 0,
            size: 99,
          },
        }).then(async (res) => {
          if ((await res) && (await res.data.code) === 200) {
            this[map.arrayKey] = _.clone(res.data.data);
          }
        });
      });
    },
    async getExamineOrganType() {
      try {
        await this.$axios({
          method: 'get',
          url: '/PROXY-Remote/organs/listAllOrgans',
        }).then((res) => {
          if (res && res.data.code === 200) {
            res.data.data.forEach((element) => {
              this.organDict.push({
                dicName: element.name,
                dicCode: element.id,
              });
            });
          }
        });
      } catch (e) {
        console.log(`请求失败  ${e}`);
      }
    },
    async appAllDataRequest() {
      let _this = this;
      if (_this.filterForm.scanRange && _this.filterForm.scanRange.length > 0) {
        let scanTimeStart = '';
        let scanTimeEnd = '';
        [scanTimeStart, scanTimeEnd] = _this.filterForm.scanRange;
        _this.filterForm.scanDateStart = moment(scanTimeStart)
          .format('YYYY-MM-DD hh:mm:ss')
          .replace(' ', ' ');
        _this.filterForm.scanDateEnd = moment(scanTimeEnd)
          .format('YYYY-MM-DD hh:mm:ss')
          .replace(' ', ' ');
      } else {
        _this.filterForm.scanDateStart = '';
        _this.filterForm.scanDateEnd = '';
      }
      await _this
        .$axios({
          // 详见 axios 请求配置项
          method: 'POST',
          url: '/PROXY-Remote/diagnosis/comQuery',
          data: _this.filterForm,
        })
        .then((res) => {
          // 请求失败
          if (res.data.code !== 200) {
            throw new Error(res.data);
          }
          _this.loading = false;
          // 请求成功
          const result = res.data;
          console.log('result', result);
          if (result.data.length > 0) {
            _this.appAllTable.pageInfo = result.pageInfo;
            _this.appAllTable.data = result.data;
            _this.appAllTable.pageInfo.page += 1;
            for (let i = 0; i < _this.appAllTable.data.length; i++) {
              _this.appAllTable.data[i].biopsyCount =
                _this.appAllTable.data[i].biopsyList.length;
              let annoCount = null;
              for (
                let j = 0;
                j < _this.appAllTable.data[i].biopsyList.length;
                j++
              ) {
                if (_this.appAllTable.data[i].biopsyList[j].annotationsList) {
                  annoCount += Number(
                    _this.appAllTable.data[i].biopsyList[j].annotationsList
                      .length
                  );
                } else {
                  annoCount += 0;
                }
              }
              console.log('ancount', annoCount);
              _this.appAllTable.data[i].annoCount = annoCount;
            }
          } else {
            _this.appAllTable.pageInfo = result.pageInfo;
            _this.appAllTable.data = result.data;
            _this.appAllTable.pageInfo.page += 1;
          }
        });
    },

    toggleExpansion() {
      this.showExpansion = !this.showExpansion;
    },
    search() {
      this.loading = true;
      this.appAllDataRequest();
    },
    appAllTablePageJumpTo(val) {
      itemsCurrentPage.set(val);
      this.filterForm.page = val - 1;
      this.appAllDataRequest();
    },
    // 每页显示数量改变
    appAllTableSizeChange(val) {
      this.filterForm.size = val;
      // this.appAllTable.pageInfo.page = 1;
      this.appAllDataRequest();
    },
    rolesTableButtonClick(functionKey, row) {
      // console.log('this[functionKey](row);', functionKey, row);
      this[functionKey](row);
    },
    checkDetail(row) {
      console.log('row-checkDetail', row);
      this.$store.commit('setPropertyGeneral', {
        key: 'diagnosis',
        value: {
          id: row.id,
          pathologyId: row.pathologyId,
        },
      });
      sessionStorage.setItem('pathologyId', row.pathologyId);
      sessionStorage.setItem('pDiagnosisType', null);
      this.$router.push('/diagnosis/detail');
    },
    previewReport(row) {
      console.log('row-previewReport', row);
      const { state } = this.$store;
      const userId = state.user.id;
      const width = window.screen.availWidth + 10;
      const height = window.screen.availHeight + 10;
      window.open(
        `/detail/preview/${userId}/${row.pathologyId}`,
        '_blank',
        `location=no,width=${width},height=${height}`
      );
    },
    biopsyPicture(row) {
      this.$store.commit('setPropertyGeneral', {
        key: 'diagnosis',
        value: {
          id: row.id,
          pathologyId: row.pathologyId,
        },
      });
      console.log('row-biopsyPicture', row);
      this.$router.push('/diagnosis/detail-biopsy-images');
    },
    biopsyMark(row) {
      this.$store.commit('setPropertyGeneral', {
        key: 'diagnosis',
        value: {
          id: row.id,
          pathologyId: row.pathologyId,
        },
      });
      console.log('row-biopsyMark', row);
      this.$router.push('/diagnosis/detail-biopsy-mark');
    },
    detailClose() {
      this.detailVisible = false;
    },
    selectionChange(selection) {
      this.selectedList = selection;
    },
    handleSelectAll(row) {
      this.selectedList = row;
    },
  },
};
</script>

<style scoped>
.expansion {
  width: 30px;
  height: 30px;
  display: inline;
  font-size: 28px;
  line-height: 30px;
  margin-top: 25px;
  vertical-align: middle;
  color: #10a1df;
  cursor: pointer;
}
</style>
